//
//  MYOAuthViewController.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/13.
//  Copyright © 2016年 Magic Yu. All rights reserved.
/*d8f6e7557416fdaf0ad7393c45061c7a*/

//1.使用webView登录授权的页面

import UIKit
import SVProgressHUD



class MYOAuthViewController: UIViewController {

    let webView = UIWebView()
    //自定义根视图为webView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置导航条
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "remAccount")

        //使用webView加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)

    }
    
    //在视图将要消失的时候移除弹框
    override  func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //关闭页面
    @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充账号密码
    @objc private func remAccount() {
        
    //将js转换为swift
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='2418989905@qq.com',document.getElementById('passwd').value='77qiqi1212;'")
    }
}

//遵守webView的协议
extension MYOAuthViewController: UIWebViewDelegate {

    //开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        //开启等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //取消用户等待指示器
        SVProgressHUD.dismiss()
        //设置Title 在其他方法中无效
        title = webView.stringByEvaluatingJavaScriptFromString("document.title")
    }
    
    //在授权成功的回调页中获取授权code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        
        //满足字符串包含code=
        let flag = "code="
        if urlString.containsString(flag) {
            
            //授权成功
            let range = urlString.rangeOfString(flag)!
//            print(range)  //24..<29
            let code = urlString.substringFromIndex(range.endIndex)
            
            //print(code)  //c00653f305d7b0137802673ca2195252
            
            
            //使用授权码  获取accesstoken
//            loadAccessToken(code)
            //让userAccountViewModel去做事
            MYUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                if !isSuccess {
                    //表示登录失败
                    SVProgressHUD.showErrorWithStatus(AppError)
                    return
                }
                
                //表示登录成功
                //TODO
                //跳转到欢迎页面 需要头像+用户名
                //单例对象的模型属性有值么?  没有赋值 所以没有值
                
                //跳转到欢迎页面
                
//                SVProgressHUD.showSuccessWithStatus("登录成功")
                //OAuth是一个modal出来的页面 需要手动dismiss 不然会造成无法释放
                //页面跳转的时候 可以看到后面页面的视图 取消动画即可屏蔽
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //页面释放后完成跳转
                    NSNotificationCenter.defaultCenter().postNotificationName(MYSwitchController, object: nil)
                })
            })
            
            //获取accesstoken后不加载授权成功的回调页面 留在APP
            return false
            
        }
//        print(urlString) 
        return true
    }
    
    
        
}











